import { useState, useEffect, useCallback } from "react"
import { getPaginationRequestParams } from '@/utils/pagination/helper'

import { PageResult, updatePageResult } from '@/utils/pagination/page.result'
import { postJson, postPaginationJson } from '@/utils/http/linitly.request.js'

import { FIND_ALL_URL, DELETE_BY_ID_URL } from '@/constant/common/common'

const useRD = (
  // 请求的路由中缀
  urlInfix,
  // 查询表单ref，不使用的时候可以传null
  searchFormRef,
  // 是否使用分页
  usePagination = true,
  // 开始就查询
  findFromStart = true,
) => {

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const memoizedFindAll = useCallback(findAll, [urlInfix])
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const memoizedFindAllPagination = useCallback(findAllPagination, [urlInfix])

  // 显示表格的loading属性
  const [ tableLoading, setTableLoading ] = useState(false)
  // 分页数据，包括分页信息和结果业务数据数组
  const initPageResult = new PageResult(usePagination ? memoizedFindAllPagination : memoizedFindAll, usePagination)
  const [ pageResult, setPageResult ] = useState(initPageResult)

  useEffect(() => {
    findFromStart && (usePagination ? memoizedFindAllPagination() : memoizedFindAll())
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [findFromStart, usePagination, urlInfix])

  // 查询全部业务数据的方法，同时使用分页
  function findAllPagination() {
    const searchFormValues = searchFormRef ? (searchFormRef.current ? searchFormRef.current.getFormValues() : {}) : {}
    const requestParams = getPaginationRequestParams(arguments, pageResult.pagination, searchFormValues)
    setTableLoading(true)
    postPaginationJson(urlInfix + FIND_ALL_URL, requestParams)
    .then((res) => {
      setPageResult(updatePageResult(pageResult, res))
    }).finally(() => {
      setTableLoading(false)
    })
  }

  // 查询全部业务数据的方法，不使用分页
  function findAll() {
    const searchFormValues = searchFormRef ? (searchFormRef.current ? searchFormRef.current.getFormValues() : {}) : {}
    setTableLoading(true)
    postJson(urlInfix + FIND_ALL_URL, searchFormValues)
    .then((res) => {
      setPageResult({...pageResult, data: res})
    }).finally(() => {
      setTableLoading(false)
    })
  }

  // 根据id删除的方法
  function deleteById(id) {
    return () => postJson(urlInfix + DELETE_BY_ID_URL + '/' + id)
  }

  return [ tableLoading, pageResult, deleteById, usePagination ? memoizedFindAllPagination : memoizedFindAll ]
}

export default useRD
